package com.kehutong.common.util;


import org.coraframework.json.JSONArray;
import org.coraframework.util.Objects;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;

/**
 * 转换工具类
 * @Author jian Ye
 * @date: 2021-07-29
 */
public class ConvertUtils {


    /**
     * 将对象转换成String，如果对象为null将对象转换成 "--" 字符串
     * @param o
     * @return
     */
    public static String toNoNullString(Object o){
        if(isEmpty(o)){
            return "--";
        }
        return o.toString();
    }

    /**
     * 替换JSONArray字符串
     * @param array
     * @param inputParam
     * @param paramValue
     * @return
     */
    public static JSONArray replaceString2JSONArray(JSONArray array, String inputParam, String paramValue) {
        JSONArray jsonArray = new JSONArray();
        if (Objects.isEmpty(array)) {
            return jsonArray;
        }
        Object[] objects = array.stream().toArray();
        for (int i = 0; i < objects.length; i++) {
            String object = (String)objects[i];
            String s = object.replaceAll(inputParam, paramValue);
            jsonArray.add(s) ;
        }
        return jsonArray;
    }


    public static String formatHouseBuildName(String buildName){
        if(!Objects.isEmpty(buildName) && !buildName.contains("栋")){
            buildName += "栋";
        }
        return buildName;
    }


    public static String formatHouseUnitName(String unitName){
        if(!Objects.isEmpty(unitName) && !unitName.contains("单元")){
            unitName += "单元";
        }
        return unitName;
    }


    private static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        } else if (obj instanceof Optional) {
            return !((Optional)obj).isPresent();
        } else if (obj instanceof CharSequence) {
            return ((CharSequence)obj).length() == 0;
        } else if (obj.getClass().isArray()) {
            return Array.getLength(obj) == 0;
        } else if (obj instanceof Collection) {
            return ((Collection)obj).isEmpty();
        } else {
            return obj instanceof Map ? ((Map)obj).isEmpty() : false;
        }
    }
}
